<template >
  <div class="one">
    <!-- 搜索框 -->

    <!-- 搜索框 -->

    <el-form :inline="true" :model="selectUser" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="selectUser.user" placeholder="搜索"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="userSelect" :plain="true" type="reference"
          >搜索</el-button
        >

        <!-- 添加按钮 -->
        <el-button type="primary" @click="releaseshops">添加商品</el-button>
        <!-- 刷新页面按钮 -->
        <el-button type="primary" @click="refresh">刷新</el-button>
      </el-form-item>
    </el-form>
    <div
      style="
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
      "
    >
      <el-table :data="tableData" border style="width: auto">
        <el-table-column fixed prop="id" label="商品Id" width="70">
        </el-table-column>
        <el-table-column prop="shopTitle" label="商品标题" width="auto">
        </el-table-column>
        <el-table-column label="商品封面图" width="280">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-image
                style="
                  width: auto;
                   height: 120px;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                "
                :src="'http://localhost:5000/' + scope.row.surfacePlot"
                fit="scale-down"
              ></el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="auto">
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="auto">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="auto">
          <template slot-scope="scope" style="width=300px">
            <el-button
              @click="handleEdit(scope.$index, scope.row)"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              value="Show Message"
              >修改</el-button
            >
            <el-button
              @click="handleDelete(scope.$index, scope.row)"
              type="primary"
              size="mini"
              style="background-color: red"
              icon="el-icon-delete"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageIndexChange"
        :current-page="pager.pageIndex"
        layout="total, prev, pager, next, jumper"
        :total="pager.rowsTotal"
        background
      >
      </el-pagination>
    </div>

    <!-- 模态框，用于用户的增加和修改 -->
    <el-dialog title="商品添加" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="商品标题" :label-width="formLabelWidth">
          <el-input
            v-model="form.userMsgForm.title"
            placeholder="请输入标题"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品内容描述" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            autosize
            placeholder="请输入内容"
            v-model="form.userMsgForm.content"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            v-model="form.userMsgForm.remark"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <div id="upload">
          <label class="el-form-item__label" style="width: 80px"
            >上传图片</label
          >
          <!--elementui的上传图片的upload组件-->
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            action="#"
            accept="image/png,image/gif,image/jpg,image/jpeg"
            :limit="1"
            multiple
            :auto-upload="false"
            :http-request="uploadPicture"
            :before-upload="uploadIfFrom"
            :on-exceed="maxFile"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过2M
            </div>
          </el-upload>
        </div>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑模态框 -->
    <el-dialog title="商品修改" :visible.sync="dialogUpForm">
      <div slot="footer" class="dialog-footer">
        <el-button @click="upFormCall">取 消</el-button>
        <el-button type="primary" @click="upFormOk">确 定</el-button>
      </div>
      <el-form :model="form">
        <el-form-item label="商品标题" :label-width="formLabelWidth">
          <el-input
            v-model="form.userMsgForm.title"
            placeholder="请输入标题"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input
            v-model="form.userMsgForm.remark"
            placeholder="请输入备注"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <div id="upload">
          <label class="el-form-item__label" style="width: 80px"
            >上传图片</label
          >
          <!--elementui的上传图片的upload组件-->
          <el-upload
            ref="upload"
            class="upload-demo"
            drag
            action="#"
            accept="image/png,image/gif,image/jpg,image/jpeg"
            :limit="1"
            multiple
            :auto-upload="false"
            :http-request="uploadPicture"
            :before-upload="uploadIfFrom"
            :on-exceed="maxFile"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过2M
            </div>
          </el-upload>
        </div>

        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// import {
//   fileUpload,
//   selectAllAdminJournalism,
//   upshop,
//   deleteshop,
// } from "../../api/users";
import { getToken } from "../../utils/auth";
import jwtDecode from "jwt-decode";

export default {
  data() {
    return {
      // 更新模态框
      upForm: {
        id: "",
        isRecommend: false,
        status: true,
      },
      switchValue: true,
      formLabelWidth: "120px",
      dialogImageUrl: "",
      dialogVisible: false,

      form: {
        // 商品id
        id: "",
        userMsgForm: {
          //   输入框中的数据
          remark: "",
          title: "",
          content: "",
        },
      },
      dialogFormVisible: false,
      dialogUpForm: false,
      tableData: [
        {
          id: 1,
          shopTitle: "并夕夕9.9包邮",
          url: "",
          status: "上架中",
          remark: "无",
        },
      ],
      pager: {
        pageIndex: 1,
        pageSize: 10,
        rowsTotal: 30,
      },
      // 查询用户
      selectUser: {
        user: "",
      },
    };
  },

  // provide / inject（注入依赖） 组合刷新页面
  inject: ["reload"],

  mounted() {
    this.fetchData(this.pager);
  },

  methods: {
    // 发布商品
    releaseshops() {
      this.dialogFormVisible = true;
    },
    // 查询商品
    // 分页
    // 页面页码改变时，重新拉取数据
    handlePageIndexChange(val) {
      // console.log(val);
      this.pager.pageIndex = val > 0 ? val : 1;
      this.fetchData(this.pager);
    },
    // 页面大小改变时，重新拉取数据
    handlePageSizeChange(val) {
      // console.log(val);
      this.pager.pageSize = val;
      this.fetchData(this.pager);
    },
    // 拉取后台数据（带分页）
    fetchData(pager) {
      selectAllAdminJournalism(pager).then((data) => {
        // console.log(data.data.data);
        // 有无数据是否推荐转换
        data.data.data.forEach((item) => {
          // console.log(item.isRecommend);
          console.log(item);
          // 状态转换
          if (item.status === false) {
            item.status = "已下架";
          } else {
            item.status = "上架中";
          }
          // 有无数据备注转换
          if (item.remark === "") {
            item.remark = "暂无";
          } else {
            item.remark = item.remark;
          }
          // 有无数据图片转换
          if (item.surfacePlot === null) {
            item.surfacePlot = "暂无图片";
          } else {
            item.surfacePlot = item.surfacePlot;
          }
        });

        this.tableData = data.data.data;
        this.pager = data.data.pager;
        // this.loading = false;
      });
    },

    // 上传商品
    //   文件超出最大上传数时的钩子
    maxFile() {
      this.$notify.error({
        title: "错误",
        message: "超出最大上传文件数咯",
      });
    },
    //   上传文件之前的钩子，参数为上传的文件，若返回 false 或者返回 Promise 且被 reject，则停止上传。
    uploadIfFrom(file) {
      console.log("before");

      if (
        !(
          file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg"
        )
      ) {
        this.$notify.error({
          title: "错误",
          message:
            "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
        });
        return false;
      }

      let size = file.size / 1024 / 1024 < 2;
      if (!size) {
        this.$notify.error({
          title: "错误",
          message: "图片大小必须小于2M",
        });
        return false;
      }
    },

    // 覆盖默认的上传行为，可以自定义上传的实现
    uploadPicture(file) {
      // 获取file中的文件file
      var fileObj = file.file;
      // 获取用户id（引入token后从token中获取）
      var id = jwtDecode(getToken()).userId;

      //  新建一个FormData储存文件
      var fileFrom = new FormData();
      //   将fileObj存入FormData中
      fileFrom.append("imageFile", fileObj);
      //将用户数据存入FormData中
      fileFrom.append("title", this.form.userMsgForm.title);
      fileFrom.append("content", this.form.userMsgForm.content);
      fileFrom.append("remark", this.form.userMsgForm.remark);
      fileFrom.append("userId", id);
      //   用api接口提交(直接提交整个FormData)
      fileUpload(fileFrom)
        .then((data) => {
          // console.log(data);
          //上传成功后清空上传列表
          // this.$refs["upload"].clearFiles();
          this.form.userMsgForm.title = "";
          this.form.userMsgForm.content = "";
          this.form.userMsgForm.remark = "";
          // 退出模态框
          this.dialogFormVisible = false;
          // 插入显示在页面的数组中
          this.tableData.unshift(data.data);
          console.log(data.data);
          // 清空图片
          this.$refs.upload.clearFiles();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 手动点击提交按钮触发
    onSubmit() {
      // 判断新闻标题和新闻内容和封面图片是否为空
      if (
        this.form.userMsgForm.title !== "" &&
        this.form.userMsgForm.content !== ""
      ) {
        // 判断新闻封面图是否为空
        if (this.$refs.upload.uploadFiles.length > 0) {
          // console.log(this.$refs.upload);
          // 提交upload文件上传动作
          this.$refs.upload.submit();
        } else {
          this.$notify.error({
            title: "错误",
            message: "请上传商品封面图",
          });
        }
      } else {
        this.$notify.error({
          title: "错误",
          message: "商品标题、商品内容不能为空",
        });
      }
    },

    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 删除商品的接口
          deleteshop(row.id)
            .then((data) => {
              // console.log(data.code);
              if (data.code === 1000) {
                // 删除成功
                // console.log(data);
                this.$message({
                  showClose: true,
                  message: "删除商品成功",
                  type: "success",
                });
                // 使用splice删除tableData数组里面从下标为index开始的第一个数
                this.tableData.splice(index, 1);
              } else if (data.code === 1001) {
                this.$message({
                  showClose: true,
                  message: "删除商品失败",
                  type: "error",
                });
              }
            })
            .catch((err) => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // // 商品修改
    handleEdit(index, row) {
      console.log(index);
      this.dialogUpForm = true;
      // console.log(row.id);
      this.upForm.id = row.id;
    },
    //修改判断
    upFormOk() {
      // console.log(this.upForm.id);
      var id = this.upForm.id;
      var status = this.upForm.status;
      // console.log(status);
      var data = { status };
      // console.log(data);
      //商品修改接口
      upshop(id, data)
        .then((data) => {
          console.log(data);
          this.dialogUpForm = false;
          this.reload();
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 商品修改取消事件
    upFormCall() {
      this.dialogUpForm = false;
    },

    handleCancel() {
      this.dialogFormVisible = false;
    },
    // 用户查询按钮
    userSelect() {
      // console.log(this.selectUser.user);
      var searchContent = this.selectUser.user;
      // console.log(searchContent);
      if (searchContent !== "") {
        // 搜索框存在类容
        postSelectUser(searchContent)
          .then((data) => {
            console.log(data);
            if (data.data.length != 0) {
              // console.log(3232);
              // 有查询到数据
              // console.log(data.data);

              this.tableData = data.data;
            } else {
              // 未查询到数据
              this.$message({
                message: "未搜索到数据哦",
                type: "warning",
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        // 搜索框为空
        this.$message({
          message: "搜索框不能为空哦",
          type: "warning",
        });
      }
    },
    // 刷新按钮点击事件
    refresh() {
      this.reload();
    },
  },
};
</script>
<style scoped>
.one {
  width: 100%;
  height: 80vh;
}
.block {
  text-align: center;
}
</style>